package com.zl.tby.screen.service.impl;

import com.zl.tby.core.base.enums.TbyFileTypeEnum;
import com.zl.tby.dto.TbyResearchActivitiesQuery;
import com.zl.tby.model.*;
import com.zl.tby.screen.service.ITbyEducationScreenService;
import com.zl.tby.screen.vo.DbContextResultBean;
import com.zl.tby.screen.vo.education.TbyActivitiesStatisticBean;
import com.zl.tby.screen.vo.education.TbyAnimalPlantViewStatistic;
import com.zl.tby.screen.vo.education.TbyCameraStatisticBean;
import com.zl.tby.screen.vo.education.TbyEducationResourceScreenBean;
import com.zl.tby.service.ITbyEducationResourceService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 科研宣教-大屏
 * @author changpeng
 * @version 1.0
 * @since 2024/8/15 20:22
 */
@Component
public class TbyEducationScreenServiceImpl implements ITbyEducationScreenService {

    @Db
    private DbContext db;
    @Inject
    private ITbyEducationResourceService tbyEducationResourceService;

    @Override
    public TbyCameraStatisticBean cameraStatistic() {
        TbyCameraStatisticBean vo = new TbyCameraStatisticBean();
        try {
            vo.setCameraCount(db.table("tby_camera_info").selectCount());
            List<DbContextResultBean> animalPlantList = db.table("tby_education_view").whereEq("category", "WZ").selectList("count(distinct business_id) as number1", DbContextResultBean.class);
            vo.setAnimalPlantCount(animalPlantList.get(0).getNumber1());
            List<DbContextResultBean> countList = db.table("tby_education_view").whereEq("category", "WZ").groupBy("type").selectList("type str1, count(id) number1", DbContextResultBean.class);
            for (DbContextResultBean db : countList) {
                if (StringUtils.isEmpty(db.getStr1())) {
                    continue;
                }
                if (db.getStr1().equals(TbyFileTypeEnum.IMAGE.toString())) {
                    vo.setImageCount(db.getNumber1());
                } else if (db.getStr1().equals(TbyFileTypeEnum.VIDEO.toString())) {
                    vo.setVideoCount(db.getNumber1());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return vo;
    }

    @Override
    public List<TbyAnimalPlantViewStatistic> animalPlantShopOrder(Integer limit) {
        DbTableQuery query = db.table("tby_education_view v")
                .innerJoin("tby_animal_plant ap").onEq("v.business_id", "ap.id")
                .whereEq("v.category", "WZ")
                .groupBy("v.business_id, ap.ch_name")
                .orderBy("count(v.id) desc");
        if (limit == null) {
            limit = 5;
        }
        query.limit(limit);
        try {
            Long total = db.table("tby_education_view").whereEq("category", "WZ").selectCount();
            List<TbyAnimalPlantViewStatistic> dbList = query.selectList("count(v.id) as shot_count, v.business_id, ap.ch_name business_name", TbyAnimalPlantViewStatistic.class);
            dbList.forEach(item -> {
                item.setTotal(total);
            });
            return dbList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<TbyActivitiesStatisticBean> activitiesStatistic(TbyResearchActivitiesQuery query) {
        DbTableQuery dbTableQuery = db.table("tby_research_activities ra")
                .innerJoin("tby_category_dict categoryDict").onEq("ra.category_id", "categoryDict.id")
                .innerJoin("tby_category_dict typeDict").onEq("ra.type_id", "typeDict.id")
                .whereTrue()
                .andIf(StringUtils.isNotEmpty(query.getCategoryCode()), "categoryDict.code = ?", query.getCategoryCode())
                .andIf(StringUtils.isNotEmpty(query.getHoldDateBegin()), "ra.hold_date >= ?", query.getHoldDateBegin() + " 00:00:00")
                .andIf(StringUtils.isNotEmpty(query.getHoldDateBegin()), "ra.hold_date <= ?", query.getHoldDateEnd() + " 23:59:59");
        List<TbyActivitiesStatisticBean> dbList = new ArrayList<>();
        try {
            long total = dbTableQuery.selectCount();
            dbTableQuery.groupBy("ra.type_id, typeDict.code");
            dbList = dbTableQuery.selectList("ra.type_id, typeDict.code as type_code, typeDict.name as type_name, count(ra.id) as value", TbyActivitiesStatisticBean.class);
            dbList.forEach(item -> {
                item.setTotal(total);
                item.cal();
            });
            Collections.sort(dbList, Comparator.comparingDouble(TbyActivitiesStatisticBean::getPercentage).reversed());
            TbyActivitiesStatisticBean.resetPercentage(dbList);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dbList;
    }

    @Override
    public TbyEducationResourceScreenBean educationResourceStatistic() {
        TbyEducationResourceScreenBean entity = new TbyEducationResourceScreenBean();
        try {
            // 宣教馆面积
            List<TbyEducationRoom> roomList = getRoomOrSteleCount("tby_education_room", "*", TbyEducationRoom.class);
            entity.fillRoomInformation(roomList);
            // 解放碑数量
            List<TbyEducationStele> steleList = getRoomOrSteleCount("tby_education_stele", "*", TbyEducationStele.class);
            entity.setFillSteleInformation(steleList);
            // 自然教育广场
            List<TbyEducationSquare> squareList = getRoomOrSteleCount("tby_education_square", "*", TbyEducationSquare.class);
            entity.setFillSquareArea(squareList);
            // 自然路径长度
            List<TbyEducationRoad> roadList = getRoomOrSteleCount("tby_education_road", "*", TbyEducationRoad.class);
            entity.setFillRoadInformation(roadList);
            TbyEducationResource resource = this.tbyEducationResourceService.getDetail();
            entity.fillResource(resource);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return entity;
    }

    @Override
    public TbyEducationResourceScreenBean educationPersonTrain(TbyResearchActivitiesQuery query) {
        TbyEducationResource resource = this.tbyEducationResourceService.getDetail();
        TbyEducationResourceScreenBean entity = new TbyEducationResourceScreenBean();
        entity.setEducationPerson(resource.getEducationPerson());
        entity.setVolunteer(resource.getVolunteer());
        entity.setTrainCount(0L);
        try {
            entity.setTrainCount(db.table("tby_research_activities")
                    .whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getHoldDateBegin()), "hold_date >= ?", query.getHoldDateBegin())
                    .andIf(StringUtils.isNotEmpty(query.getHoldDateEnd()), "hold_date <= ?", query.getHoldDateEnd()).selectCount());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return entity;
    }

    private <T> List<T> getRoomOrSteleCount(String tableName, String column, Class<T> clz) {
        try {
            return db.table(tableName).whereTrue().selectList(column, clz);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ArrayList<>();
    }
}
